﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class RoadController : MonoBehaviour
{

    #region Vars
    string tag = "RoadController";
	static int tc = 0;
	public float speed = 2f;
	public float horizontalDirection = -1; //move from right to left

	public List<GameObject> road;
	int road_length;
	public List<GameObject> enemy;
	int enemy_length;

    public List<GameObject> coin;
    public List<GameObject> fuel;

    public GameObject[] coinArr;
    public GameObject[] fuelArr;

	float[] randomArr = new float[2] {1.1f, -1.1f};
	public static RoadController rc;

    // Max coin and fuel base on screen size
    int maxCoin;
    int maxFuel;
    int maxEnemy;
    int maxBg;

    // Random coin and fuel appear in screen
    int CoinNumber;
    int FuelNumber;

    GameObject[] fuelObj, coinObj, enemyObj, roadObj;
    

    GameObject leftBox, meterCounter;

    GameObject mainBG;

    #endregion

    #region ClassCore
    // Use this for initialization
	void Start () {

        // Init all data for game
        InitData();

        DrawBG();

        // Fake singleton pattern
        rc = this;
	}

    // Update is called once per frame
    void Update()
    {
        if (GLOBAL.s_isGameOver == true)
        {
            GLOBAL.s_fSpeed = 0f;
        }
        if (GLOBAL.s_iMeterCounter % 20 == 0 && GLOBAL.s_iMeterCounter > 21)
        {
            SpeedIncrease();
        }

        // Move left base on speed, speed will change 
        transform.Translate(new Vector3(GLOBAL.s_fSpeed * horizontalDirection * Time.deltaTime, 0, 0));

    }


    #endregion


    #region Init Data
    /// <summary>
    /// Get data about max number of coin, fuel, enemy appears in view
    /// </summary>
    void GetData()
    {
        maxCoin = 5;
        maxFuel = 2;
        maxEnemy = 5;
        maxBg = 4;
    }


    /// <summary>
    /// Init data for loop
    /// </summary>
    void InitData()
    {
        GetData();

        mainBG = GameObject.FindGameObjectWithTag("MainBG");

        CreateRoad();

        CreateCollisionWall();

        CreateEnemy();

        CreateCoin();

        CreateFuel();

    }


    void CreateRoad()
    {
        int i = 0;
        roadObj = new GameObject[maxBg];

        for (i = 0; i < maxBg; i++)
        {
            roadObj[i] = Instantiate(Resources.Load("Road")) as GameObject;
            roadObj[i].transform.parent = mainBG.transform;
        }
    }


    /// <summary>
    /// Create collision wall using resource load
    /// </summary>
    void CreateCollisionWall()
    {
        leftBox = Instantiate(Resources.Load("CollisionWall")) as GameObject;
        meterCounter = Instantiate(Resources.Load("CollisionWall")) as GameObject;
        GameObject player = GameObject.FindGameObjectWithTag("Player");
        meterCounter.transform.parent = player.transform;
        meterCounter.transform.position = player.transform.position;
    }



    /// <summary>
    /// Create an array of list enemy
    /// </summary>
    void CreateEnemy()
    {
        int i = 0;

        enemyObj = new GameObject[maxEnemy];

        for (i = 0; i < maxEnemy; i++)
        {
            enemyObj[i] = Instantiate(Resources.Load("Enemy")) as GameObject;
            enemyObj[i].transform.parent = mainBG.transform;
        }

    }


    void CreateFuel()
    {
        int i = 0;

        fuelObj = new GameObject[maxFuel];

        for (i = 0; i < maxFuel; i++)
        {
            fuelObj[i] = Instantiate(Resources.Load("Fuel")) as GameObject;
            fuelObj[i].transform.parent = mainBG.transform;
        }
    }

    void CreateCoin()
    {
        coinObj = new GameObject[maxCoin];
        int i = 0;
        
        for (i = 0; i < maxCoin; i++)
        {
            coinObj[i] = Instantiate(Resources.Load("Coin")) as GameObject;
            coinObj[i].transform.parent = mainBG.transform;
        }

    }

    #endregion

    #region Resource pos

    void DrawBG()
    {

        int i = 1;
        // Draw road
        for (i = 1; i < maxBg; i++)
        {
            roadObj[i].transform.position = new Vector3(roadObj[i - 1].transform.position.x + roadObj[0].renderer.bounds.size.x, 0, 5);
        }

        
        // End draw road
        //Debug.Log("ngdlong_" + tc++ + "_" + tag + " " + "RepeatRoad");
        //road[0].transform.position = new Vector3(road[road_length - 1].transform.position.x + road[0].renderer.bounds.size.x, 0, 5);

        //GameObject troad = road[0];
        //road.RemoveAt(0);
        //road.Add(troad); 
    }


    void RandomItems()
    {
        int maxItemsPerRound = Random.Range(3, maxCoin);


    }

    void RandomEnemy()
    {

    }

    
    #endregion

    #region Make loop
    #endregion

    #region old_code
    void GetListRoad()
    {

		road = new List<GameObject>();
		GameObject[] troad = GameObject.FindGameObjectsWithTag ("Road");
		road_length = troad.Length;

        
		// Sort list base on posX
		for (int i = troad.Length-1; i >=0 ; i--) 
		{
			for (int y = troad.Length-1; y >= 0; y--)
			{
				if (troad[i].transform.position.x > troad[y].transform.position.x){
					GameObject temp = troad[y];
					troad[y] = troad[i];
					troad[i] = temp;
				}
			}
		}

        // Add to list
		foreach(GameObject r in troad)
		{
			road.Add(r);
		}
	}

	
	void GetListEnemy(){
		enemy = new List<GameObject>();
		GameObject[] tenemy = GameObject.FindGameObjectsWithTag ("Enemy");
		enemy_length = tenemy.Length;

//		for (int i = tenemy.Length-1; i >=0 ; i--) 
//		{
//			enemy.Add(tenemy[i]);
//		}
//

		// Sort list base on posX
		for (int i = tenemy.Length-1; i >=0 ; i--) 
		{
			for (int y = tenemy.Length-1; y >= 0; y--)
			{
				if (tenemy[i].transform.position.x > tenemy[y].transform.position.x){
					GameObject temp = tenemy[y];
					tenemy[y] = tenemy[i];
					tenemy[i] = temp;
				}
			}
		}
		
		foreach(GameObject e in tenemy)
		{
			enemy.Add(e);
		}
		Debug.Log("Make break point");
	}

    void Sort(List<GameObject> list, GameObject[] arr)
    {
        for (int i = arr.Length - 1; i >= 0; i--)
        {
            for (int y = arr.Length - 1; y >= 0; y--)
            {
                if (arr[i].transform.position.x > arr[y].transform.position.x)
                {
                    GameObject temp = arr[y];
                    arr[y] = arr[i];
                    arr[i] = temp;
                }
            }
        }

        foreach (GameObject e in arr)
        {
            list.Add(e);
        }
    }

	

	void SpeedIncrease()
	{
		float increaseStep = 0f;
		switch (GLOBAL.s_iDifficultLevel) {
		case 0:
				increaseStep = 0.2f;
			break;
		case 1:
				increaseStep = 0.3f;
			break;
		case 2:
				increaseStep = 0.4f;
			break;
		}

		GLOBAL.s_fSpeed += increaseStep;

	}


	public void RepeatRoad()
	{
		//Debug.Log("ngdlong_" + tc++ + "_" + tag + " " + "RepeatRoad");
		road[0].transform.position = new Vector3(road[road_length-1].transform.position.x + road[0].renderer.bounds.size.x, 0, 5);

		GameObject troad = road [0];
		road.RemoveAt (0);
		road.Add (troad);
	}

	public void RepeatCar()
	{
		//Debug.Log("ngdlong_" + tc++ + "_" + tag + " " + "RepeatCar");
		float posY;
		int random = Random.Range (0, 10);
		if ((random % 2) == 0) {
			posY = randomArr [0];
		} else {
			posY = randomArr[1];
		}
		enemy [0].transform.position = new Vector3 (enemy[enemy_length-1].transform.position.x + enemy[0].renderer.bounds.size.x + 7f, posY, 1);

		GameObject tenemy = enemy [0];
		enemy.RemoveAt (0); 
		enemy.Add (tenemy);

	}



    void SetupVariables()
    {

    }

    void RandomItem(GameObject[] items)
    {
        // Random quanity of coin and fuel appears in a screen frame
        

        

        int i = 0;
        // Init coin and fuel array
        for (i = 0; i <= CoinNumber; i++)
        {
               
        }

        for (i = 0; i <= FuelNumber; i++)
        {
            
        }




    }
    #endregion
}

